<?php
namespace App\Service;

use App\Models\WxModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class WxService extends BaseService{
    protected $appid = "";
    protected $secret = "";
    private $tmpid = "OOjNspUwDfEAd-lXjMmC-004_P8u3VxzrqgroNRM_go";
    static $template_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?";
    static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";
    static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";
    static $user_get_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" ;
    static $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
    static $code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?";

    final public function setAppid($appid) {
        $this->appid = $appid;
        return $this;
    }
    final public function setSecret($secret) {
        $this->secret = $secret;
        return $this;
    }
    public function getToken(){
        if(Cache::has('access_token')){
            $access_token = Cache::get('access_token');
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret;
            $token = $this->request_get($url);
            $token = json_decode(stripslashes($token));
            $arr = json_decode(json_encode($token), true);
            $access_token = $arr['access_token'];
            Cache::put('access_token',$access_token,7200);
        }
        return $access_token;
    }
    public function getOpenId($code){
        $url = self::$access_token_url . "appid=".$this->appid."&secret=".$this->secret."&code=".$code."&grant_type=authorization_code";
        $data = $this->request_get($url);
        Log::info(json_encode($data));
        return $data;
    }
    public function getCodeUrl($callback,$state){
        return self::$code_url."appid=".$this->appid."&redirect_uri=".urlencode($callback)."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";
    }
    public function sendMessage($openid,$name,$sb_name,$detail){
        $data = $this->messageData($openid,$name,$sb_name,$detail);
        Log::info(json_encode($data));
        $WxModel = new WxModel();
        $ACCESS_TOKEN = $WxModel->getToken();
        $url = self::$template_url.'access_token='.$ACCESS_TOKEN;
        $res = $WxModel->http_post_data($url,$data);
        Log::info(json_encode($res));
    }
    public function messageData($openid,$name,$sb_name,$detail){
        $time = date("Y-m-d H:i:s",time());
        $data = [
            'touser' => $openid,
            'template_id' => $this->tmpid,
            /*'miniprogram'=>[
                'appid'=>'wx44335037fe3a73c8',
                'pagepath'=>'pages/index/index'
            ]*/
        ];
        $data['data'] = [
            'keyword1' => ["value" => "{$sb_name}"],
            'keyword2' => ["value" => "{$time}"],
            'keyword3' => ["value" => "{$name}"],
            'keyword4' => ["value" => "{$detail}"],
        ];
        return $data;
    }
    public function getQrcodeurl($fqid) {
        $ACCESS_TOKEN = $this->getToken();
        $url = self::$qrcode_url . 'access_token=' . $ACCESS_TOKEN;
        $qrcode['expire_seconds'] = 604800;
        $qrcode['action_name'] = "QR_STR_SCENE";
        $qrcode['action_info']['scene']['scene_str'] = $fqid;
        $result = $this->http_post_data($url, $qrcode);
        $oo = json_decode($result);
        if (empty($oo->ticket)) {
            return false;
        }
        if (!$oo->ticket) {
            Log::info('getQrcodeurl falied. Error Info: getQrcodeurl get failed');
            exit();
        }
        $url = self::$qrcode_get_url . 'ticket=' . $oo->ticket . '';
        return $url;
    }
    /**
     * 获取用户详细信息
     * @param $openid
     * @param $refer_id
     */
    public function createuserinfo($openid, $refer_id) {
        $ACCESS_TOKEN = $this->getToken();
        $url = self::$user_get_url. $ACCESS_TOKEN . "&openid=" . $openid;
        $wx = new WxModel();
        $user = $wx->request_get($url);
        $user = json_decode($user, true);
        $users = array(
            'openid' => $openid,
            'nickname' => $user['nickname'],
            'avatar' => $user['headimgurl'],
            'sex' => $user['sex'],
            'status' => 1,
            'reg_time' => $user['subscribe_time'],//关注公众号的时间
            'bind_user' => $refer_id
        );
        $user_str = date('Y-m-d H:i:s') . "\t";
        foreach ($users as $key => $value) {
            $user_str .= $key . '=' . $value . "\t";
        }
        $user_str .= "\n";
        return $users;
    }
    public function http_post_data($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    public function request_get($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
}
